//
//  ITUploadManager.m
//  InTubePro
//
//  Created by seven on 2020/1/8.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITUploadManager.h"
#import "ITUserManager.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>
#import "ITImagePicker.h"
#import "ITPhotoSelectAlert.h"
#define AliyunAccessToken @"A75FoQRbABvufI79"
#define EndPoint @"oss-us-west-1.aliyuncs.com" //@"x-intube-pro.oss-us-west-1.aliyuncs.com"
#define OSS_STSTOKEN_URL [NSString stringWithFormat:@"%@%@",[AppUtils returnBaseUrl],@"/common/sts"]
#define BucketName @"x-intube-pro"
#define FilePath @"app/photo"
#import "ITUserCenterNetworkAPIManager.h"
@interface ITUploadManager()<ITImagePickerDelegate>{
    dispatch_semaphore_t _semaphore;
    UIAlertController *alertController;
}

@property(nonatomic, copy) UploadCallBack callBack;
@property(nonatomic, strong) OSSClient *client;
@property(nonatomic, assign) int scene;
@end

@implementation ITUploadManager

+ (instancetype)shareManager{
    static ITUploadManager *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [ITUploadManager new];
        [_manager initSetting:nil];
    });
    return _manager;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _semaphore = dispatch_semaphore_create(1);
    }
    return self;
}

- (void)initSetting:(void(^)(BOOL success))callback{
//    if (NSThread.isMainThread) {
//        [self performSelectorInBackground:@selector(initSetting:) withObject:callback];
//        return;
//    }
    //dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    if (_client != nil) {
        if (callback)(YES);
        //dispatch_semaphore_signal(_semaphore);
        return;
    }
    WEAKSELF;
    
    [[ITUserCenterNetworkAPIManager shareManager] requestSts:1 callback:^(NSDictionary * _Nonnull result){
        if (result == nil) {
            if (callback) callback(NO);
            //dispatch_semaphore_signal(self->_semaphore);
            return ;
        }
        NSString *securityToken = [result objectForKey:@"SecurityToken"];
        NSString *accessKeySecret = [result objectForKey:@"AccessKeySecret"];
        NSString *accessKeyId = [result objectForKey:@"AccessKeyId"];
//        accessKeyId = @"LTAI4FqkqQcFH3oRRQuv4ogV";
//        accessKeySecret = @"NbIsk4A7Yj5onXEN31t7jKJaKwKWla";

        if (securityToken && accessKeySecret && accessKeyId) {
            NSString *url = [[AppUtils returnBaseUrl] stringByAppendingString:VT_Member_STSAutheticationUpload_API];
            OSSAuthCredentialProvider *credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:url responseDecoder:^NSData * _Nullable(NSData * _Nonnull data) {
                return data;
            }];
            OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
            cfg.maxRetryCount = 3;
            cfg.timeoutIntervalForRequest = 15;
            cfg.isHttpdnsEnable = NO;
            cfg.crc64Verifiable = YES;
            
            weak_self.client = [[OSSClient alloc] initWithEndpoint:[NSString stringWithFormat:@"https://%@/",EndPoint] credentialProvider:credentialProvider clientConfiguration:cfg];
        }
        if (callback) callback(weak_self.client != nil);
        //dispatch_semaphore_signal(self->_semaphore);
    }];
}

- (void)uploadImage:(UIImage *)image callback:(void(^)(NSString * IT_NULLABLE imageUrl))callback{
    if (_client == nil) {
        [self initSetting:^(BOOL success) {
            if (!success) {
                if (callback) callback(nil);
            }else {
                [self goUploadImage:image callback:callback];
            }
        }];
    }else {
        [self goUploadImage:image callback:callback];
    }
}


-(void)goUploadImage:(UIImage *)image callback:(void(^)(NSString * IT_NULLABLE imageUrl))callback{
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // 必填字段
    put.bucketName = BucketName;
    ITMember *host = [ITUserManager  currentMember];
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@_%.0lf.png",FilePath,host.memberId,now];
    put.objectKey = filePath;
    put.uploadingData = UIImageJPEGRepresentation(image, 0.7); // 直接上传NSData
    // 设置Content-Type，可选
    put.contentType = @"application/octet-stream";
    // 设置MD5校验，可选
//    put.contentMd5 = [OSSUtil base64Md5ForFilePath:@"<filePath>"]; // 如果是文件路径
//    // put.contentMd5 = [OSSUtil base64Md5ForData:<NSData *>]; // 如果是二进制数据
    // 进度设置，可选
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
            NSString *url = [NSString stringWithFormat:@"https://%@.%@/%@",BucketName,EndPoint,filePath];
            if (callback) {
                callback(url);
            }
        } else {
            [AppUtils showInfo:[AppUtils titleForKey:@"upload failed"]];
            NSLog(@"upload object failed, error: %@" , task.error);
            if (callback) {
                callback(nil);
            }
        }
        return nil;
    }];
}


- (void)selectImageScene:(ITImageScene)scene callBcak:(UploadCallBack)callback{
    self.scene = scene;
    self.callBack = callback;
    [self clickChangePhoto];
}

- (void)selectImageScene:(ITImageScene)scene pickType:(ImagePickerType)type callBcak:(UploadCallBack)callback{
    self.scene = scene;
    self.callBack = callback;
    ITImagePicker *imagePicker = [ITImagePicker sharedInstance];
    imagePicker.delegate = self;
    [imagePicker showImagePickerWithType:type inViewController:[AppUtils findRootController] scene:_scene];
    [UIApplication sharedApplication].statusBarStyle = [AppUtils getDarkStyle];
}


#pragma mark 获取头像图片

- (void)clickChangePhoto
{
    /*
    if (![[ITUserManager shareManager] verifyLoginWithCompletion:^(BOOL loginSuccess, ITUserInfo * _Nullable userInfo) {
        
    }]) {
        return;
    }//*/
    WEAKSELF;
    
    [ITPhotoSelectAlert showWithType:7].customAction = ^(NSNumber *obj, CustomActionType idx) {
        if (obj.intValue == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                ITImagePicker *imagePicker = [ITImagePicker sharedInstance];
                imagePicker.delegate = weak_self;
                [imagePicker showImagePickerWithType:ImagePickerCamera inViewController:[AppUtils findRootController] scene:_scene];
                [UIApplication sharedApplication].statusBarStyle = [AppUtils getDarkStyle];
            });
        }else if (obj.intValue == 2){
            dispatch_async(dispatch_get_main_queue(), ^{
                ITImagePicker *imagePicker = [ITImagePicker sharedInstance];
                imagePicker.delegate = weak_self;
                [imagePicker showImagePickerWithType:ImagePickerPhoto inViewController:[AppUtils findRootController] scene:_scene];
                [UIApplication sharedApplication].statusBarStyle = [AppUtils getDarkStyle];
            });
        }
    };
}

#pragma -mark ITImagePickerDelegate
- (void)didUploadImage:(UIImage *)image url:(NSString *)imageUrl {
    if (_callBack) {
        _callBack(image, imageUrl);
    }
}

- (void)imagePicker:(ITImagePicker *)imagePicker didFinished:(UIImage *)editedImage
{
    MBProgressHUD *hud = [AppUtils showLoading];
    WEAKSELF
    [ITUploadManager.shareManager uploadImage:editedImage callback:^(NSString * _Nullable imageUrl) {
        MainDelay(0, ^{
            [weak_self didUploadImage:editedImage url:imageUrl];
            [hud hideAnimated:YES];
        });
    }];
}

- (void)imagePickerDidCancel:(ITImagePicker *)imagePicker
{
    
}

@end
